package com.jt.msg.resp;

import com.jt.msg.DataPacket;
import com.jt.utils.JT808Const;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang3.StringUtils;


/**
 * 注册应答包
 *
 * @author wang xiao
 * date 2023/8/9
 */

public class RegisterResp extends DataPacket {

    /**
     * 成功
     */
    public static final byte SUCCESS = 0;

    /**
     * 车辆已被注册
     */
    public static final byte VEHICLE_ALREADY_REGISTER = 1;

    /**
     * 无该车辆
     */
    public static final byte NOT_IN_DB = 2;

    /**
     * 终端已被注册
     */
    public static final byte TERMINAL_ALREADY_REGISTER = 3;

    /**
     * 应答流水号 2字节
     */
    private short replyFlowId;

    /**
     * 结果 1字节
     */
    private byte result;

    /**
     * 鉴权码
     */
    private String authCode;

    public RegisterResp() {
        this.getHeader().setMsgId(JT808Const.SERVER_RESP_REGISTER);
    }

    public static RegisterResp success(DataPacket msg, short flowId) {
        RegisterResp resp = new RegisterResp();
        resp.getHeader().setTerminalId(msg.getHeader().getTerminalId());
        resp.getHeader().setFlowId(flowId);
        resp.setReplyFlowId(msg.getHeader().getFlowId());
        resp.setResult(SUCCESS);
        resp.setAuthCode("SUCCESS");
        return resp;
    }

    @Override
    public ByteBuf toByteBufMsg() {
        ByteBuf bb = super.toByteBufMsg();
        bb.writeShort(replyFlowId);
        bb.writeByte(result);
        if (result == SUCCESS && StringUtils.isNotBlank(authCode)) {//成功才写入鉴权码
            bb.writeBytes(authCode.getBytes(JT808Const.DEFAULT_CHARSET));
        }
        return bb;
    }

    public short getReplyFlowId() {
        return replyFlowId;
    }

    public void setReplyFlowId(short replyFlowId) {
        this.replyFlowId = replyFlowId;
    }

    public byte getResult() {
        return result;
    }

    public void setResult(byte result) {
        this.result = result;
    }

    public String getAuthCode() {
        return authCode;
    }

    public void setAuthCode(String authCode) {
        this.authCode = authCode;
    }
}
